package situ.com.androidstudy;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HandlerActivity extends AppCompatActivity {
    public static final int UPDATE = 1;

    private Button btn;
    private TextView textView;

    // UI线程
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case UPDATE:
                    System.out.println(msg.arg1);
                    Bundle bundle = msg.getData();
                    String data = bundle.getString("data");
                    System.out.println(data);
                    textView.setText(data);
                    break;
            }
        }
    };

    // 主线程，UI线程
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        btn = (Button) findViewById(R.id.btn);
        textView = (TextView) findViewById(R.id.textView);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        for (int i = 1; i <= 10; i++) {
                            Message message = new Message();
                            message.what = UPDATE;
                            message.arg1 = i;
                            Bundle bundle = new Bundle();
                            bundle.putString("data", i * 10 + "%");
                            message.setData(bundle);
                            handler.sendMessage(message);

                            // textView.setText(i * 10 + "%");
                            try {
                                Thread.sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }).start();
            }
        });


    }
}
